package com.ada;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;

import java.lang.reflect.InvocationTargetException;

public class ScriptApp {

    public static void main(String[] args) {
        // about the execution environment of a script.
        Context cx = Context.enter();
        try {
            // Initialize the standard objects (Object, Function, etc.)
            // This must be done before scripts can be executed. Returns
            // a scope object that we use in later calls.
            Scriptable scope = cx.initStandardObjects();

            // Collect the arguments into a single string.
            String s = "out.println(3);var x=1;var c = new Counter(8); c.add();out.println(c.count);";
            for (int i=0; i < args.length; i++) {
                s += args[i];
            }
            Object wrappedOut = Context.javaToJS(System.out, scope);
            ScriptableObject.putProperty(scope, "out", wrappedOut);
            ScriptableObject.defineClass(scope, Counter.class);
            // Now evaluate the string we've colected.
            Object result = cx.evaluateString(scope, s, "<cmd>", 1, null);
            Object x = scope.get("x", scope);
            System.out.printf(x+"");
            System.out.printf(scope.get("c",scope)+"");
            // Convert the result to a string and print it.
            System.err.println(Context.toString(result));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } finally {
            // Exit from the context.
            Context.exit();
        }
    }
}
